package com.lzy.utils;

import com.lzy.security.LoginUser;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

/**
 * @author lyw
 * @Date 2023/2/2-下午1:52
 */
public class SecurityUtil {
  private static final BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();


  private SecurityUtil() {}

  public static LoginUser getLoginUser() {
    try
    {
      return (LoginUser) getAuthentication().getPrincipal();
    }
    catch (Exception e)
    {
      throw new RuntimeException("获取用户信息异常");
    }
  }

  /**
   * 获取用户账户
   **/
  public static String getUsername()
  {
    try
    {
      return getLoginUser().getUsername();
    }
    catch (Exception e)
    {
      throw new RuntimeException("获取用户账户异常");
    }
  }

  /**
   * 获取Authentication
   */
  public static Authentication getAuthentication() {
    return SecurityContextHolder.getContext().getAuthentication();
  }

  public static String encryptPassword(String password) {
    return encoder.encode(password);
  }

  public static boolean verifyPassword(String password, String secretKey) {
    return encoder.matches(password, secretKey);
  }
}
